package com.hontech.desktoppastacooker.ui.window

import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import com.hontech.desktoppastacooker.R
import com.hontech.desktoppastacooker.utils.dimenById
import kotlinx.coroutines.delay


class Dialog : MoveableWindow(
    R.layout.dialog,
    width = dimenById(R.dimen.dialog_width),
    height = dimenById(R.dimen.dialog_height),
    focusable = false
) {

    private val btnClose = view.findViewById<Button>(R.id.id_dialog_btn_close)
    private val prog = view.findViewById<ProgressBar>(R.id.id_dialog_prog)
    private val img = view.findViewById<ImageView>(R.id.id_dialog_image)
    private val tvTitle = view.findViewById<TextView>(R.id.id_dialog_tv_title)
    private val tvMsg = view.findViewById<TextView>(R.id.id_dialog_tv_msg)

    init {
        btnClose.setOnClickListener { dismiss() }
    }

    fun setMsg(msg: String) {
        tvMsg.text = msg
    }

    suspend fun success(msg: String) {
        prog.visibility = View.INVISIBLE
        img.visibility = View.VISIBLE
        tvMsg.text = msg
        img.setImageResource(R.drawable.ic_succ)

        delay(600)
        dismiss()
    }

    fun error(e: Exception) {
        prog.visibility = View.INVISIBLE
        img.visibility = View.VISIBLE
        tvMsg.text = e.message!!
        img.setImageResource(R.drawable.ic_fail)
    }

    fun showProg(title: String, msg: String) {
        prog.visibility = View.VISIBLE
        img.visibility = View.INVISIBLE
        tvTitle.text = title
        tvMsg.text = msg
        show()
    }

    fun showError(title: String, e: Exception) {
        prog.visibility = View.INVISIBLE
        img.visibility = View.VISIBLE
        tvTitle.text = title
        tvMsg.text = e.message!!
        img.setImageResource(R.drawable.ic_fail)
        show()
    }

    fun showError(title: String, msg: String) {
        prog.visibility = View.INVISIBLE
        img.visibility = View.VISIBLE
        tvTitle.text = title
        tvMsg.text = msg
        img.setImageResource(R.drawable.ic_fail)
        show()
    }

    fun showSuccess(title: String, msg: String) {
        prog.visibility = View.INVISIBLE
        img.visibility = View.VISIBLE
        tvTitle.text = title
        tvMsg.text = msg
        img.setImageResource(R.drawable.ic_succ)
        show()
    }
}

fun showSucc(title: String, msg: String): Dialog {
    val dialog = Dialog()
    dialog.showSuccess(title, msg)
    return dialog
}

fun showErr(title: String, msg: String): Dialog {
    val dialog = Dialog()
    dialog.showError(title, msg)
    return dialog
}

fun showErr(title: String, e: Exception): Dialog {
    val dialog = Dialog()
    dialog.showError(title, e.message!!)
    return dialog
}

fun showProg(title: String, msg: String): Dialog {
    val dialog = Dialog()
    dialog.showProg(title, msg)
    return dialog
}
